import React, { useState, useCallback, useEffect } from 'react'
import { SimpleSelector } from './simpleSelector'
import { NotifyType } from '../../common/enums'
import { notify } from '../../source/notify'
import { getAllMocksOfAjax } from '../../source/getData'
import { useShowModal } from './modal'
import style from './modal.scss'

export const MockSelector = ({ ajaxId, mockId, onSelectItem, readOnly = false }) => {
    const [dataSource, setDataSource] = useState([])
    const filterDataSource = useCallback(value => item => {
        return item.remark.toLowerCase().includes(value.toLowerCase())
    }, [])
    const getItemValue = useCallback(item => item.id, [])
    const renderItem = useCallback(item => item.remark, [])

    useEffect(() => {
        getAllMocksOfAjax(ajaxId)
            .then(data => setDataSource(data))
            .catch(err => notify(NotifyType.error, err))
    }, [ajaxId])

    const [quickEditorData, setQuickEditorData] = useState(null)
    const onClickQuickEdit = (item) => {
        setQuickEditorData(item)
    }

    const wrapOnClose = useCallback(() => {
        setQuickEditorData(null)
    }, [setQuickEditorData])

    const quickEditorTitle = quickEditorData ? quickEditorData.remark : ''
    const quickEditorBodyContent = quickEditorData && quickEditorData.data ? (() => {
        try {
            return JSON.stringify(JSON.parse(quickEditorData.data || {}), null, 2)
        } catch (error) {
            console.error(`parse mock data error: `, error)
            return ''
        }
    })() : ''

    const quickEditor = useShowModal({
        show: !!quickEditorData,
        title: `查看MOCK报文: ${quickEditorTitle}`,
        body: <textarea className={style['textarea']} value={quickEditorBodyContent} readOnly={true}></textarea>,
        onClose: wrapOnClose
    })

    return <React.Fragment>
        <SimpleSelector dataSource={dataSource} filterDataSource={filterDataSource}
            getItemValue={getItemValue} initValue={mockId} onSelectItem={onSelectItem}
            readOnly={readOnly} renderItem={renderItem} onClickQuickEdit={onClickQuickEdit} />
        {quickEditor}
    </React.Fragment>
}